package ch.usi.inf.pf2;

import java.io.*;


/**
 * This class contains some methods to save the data contained in a spreadsheet
 * into a file
 * 
 * @author Lorenzo Baracchi
 */
public class WriteSpreadSheetFile
{
    private Sheet sheetToWrite;
    private String fileWhereToWrite;
    private int lastOccurrence;
    private int lastRow;

    /**
     * Create the class used to write the sheet
     * 
     * @param sheetToWrite
     *            the sheet to save into the file
     * @param fileName
     *            the name of the file where to write
     */
    public WriteSpreadSheetFile(Sheet sheetToWrite, String fileName)
    {
	   this.sheetToWrite = sheetToWrite;
	   this.fileWhereToWrite = fileName + ".CSV";
	   lastOccurrence = 0;
	   lastRow = 0;
    }

    /**
     * Check if the file already exists
     * 
     * @return true if exist false otherwise
     */
    public boolean tryToOpenFile()
    {
	   File newFile = new File(fileWhereToWrite);
	   return newFile.exists();
    }

    /**
     * Return the last cell occupied in a Sheet's row
     * 
     * @param indexRow
     *            the index of the row
     * @return the index of the last column occupied
     */
    public int findLastOccurrence(int indexRow)
    {
	   for (int i = sheetToWrite.getColumns() - 1; i >= 1; i--)
		  if (!(sheetToWrite.getCell(i, indexRow).getContent().getInstance()
				.equals("")))
			 return i;
	   return 0;
    }

    /**
     * Return the number of lastRow occupied in a Sheet
     * 
     * @return the index of the last row occupied
     */
    public int findLastRow()
    {
	   for (int i = sheetToWrite.getRows() - 1; i >= 1; i--)
		  if (findLastOccurrence(i) != 0)
			 return i;
	   return 0;
    }

    /**
     * Write the sheet's contents into the file
     */
    public void writeSheet()
    {
	   if (!tryToOpenFile())
	   { // file not found
		  File toWrite = new File(fileWhereToWrite);
		  try
		  {
			 toWrite.createNewFile();
		  } catch (IOException e)
		  {
			 System.err
				    .println("Some error occurred while attemping to create the file");
			 e.printStackTrace();
		  }
		  writeLoop(toWrite);
	   } else
	   { // file found overwrite it
		  File toWrite = new File(fileWhereToWrite);
		  writeLoop(toWrite);
	   }
    }

    /**
     * Actual loop to write all the spreadsheet into the given file
     * 
     * @param toWrite
     *            the file where to write
     */
    private void writeLoop(File toWrite)
    {
	   RandomAccessFile writer = null;
	   try
	   {
		  writer = new RandomAccessFile(toWrite, "rw");
	   } catch (FileNotFoundException e)
	   {
		  // the file always exists
		  assert false;
	   }

	   lastRow = findLastRow();
	   for (int i = 1; i <= lastRow; i++)
	   {
		  lastOccurrence = findLastOccurrence(i);
		  try
		  {
			 String toWriteIn = "";
			 for (int j = 1; j <= lastOccurrence; j++)
				/*toWriteIn += "\""
					   + sheetToWrite.getCell(j, i).getContent()
							 .toString() + "\",";*/
				toWriteIn+=sheetToWrite.getCell(j, i).getContent()
				 .toString() + ",";
			 writer.writeBytes(toWriteIn + "\n");
		  } catch (IOException io)
		  {
			 System.err
				    .println("Some error occurred while try to write in the file");
		  }
	   }
    }
}